#销售换货
#销售换货，要先退回仓库，然后再出库。
class SaleExchangeController < ApplicationController
  before_filter :employee_authorize,:except=>[:sale_order_print_header,:sale_order_print_content,:sale_order_print_footer]
  before_filter :sys_before_log
  before_filter :employee_action_hx
  before_filter :privilege_filter,:except=>[:newSaleExchange]

  #对于一张销售订单，计算出当前还可以换货的数量和种类换货可以不停的换。没有数据限制。
  def getSaleOrderDetailsByIdForExchange
    saleOrderId = params[:sale_order_id]
    saleOrderDetails = SaleOrderDetail.find(:all,:select=>"sd.id,p.id as product_id,p.name as product_name,p.is_suit,sd.unit_price,p.number,p.spec,p.unit,sd.description,newrd.quantity as rd_quantity,(sum(sd.quantity) - ifnull(newrd.quantity,0)) as balance_quantity,(sd.amount/sd.quantity)*(sum(sd.quantity) - ifnull(newrd.quantity,0)) as amount,sd.discount ",:joins =>"sd
left join (select rd.product_id,sum(rd.quantity) as quantity
from sale_returned_details rd left join sale_returneds r on r.id = rd.sale_returned_id
where r.sale_order_id = "+saleOrderId+" AND r.auditing_status != '#{Constants::PASS_APPLY_CANCEL}'
group by product_id) newrd on newrd.product_id = sd.product_id
left join products p on p.id = sd.product_id
where sd.sale_order_id =  "+saleOrderId+ " group by sd.product_id having sum(sd.quantity) - ifnull(newrd.quantity,0) > 0")

    jsonStr="{totalProperty:"+saleOrderDetails.length.to_s+",root:"+saleOrderDetails.to_json()+"}"
    logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end
  
end
